package com.reggie.configuration.exceptionHandler;

import com.reggie.configuration.common.Result;
import com.reggie.configuration.myException.CustomException;
import com.reggie.configuration.myException.RepetitionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.sql.SQLIntegrityConstraintViolationException;

//参数指的是要捕获弹出异常的注解，也就是标注了这个注解的类
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class MyExceptionHandler {

    /**
     * 这个注解是要捕获的异常类型，参数就是类型
     *
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> Exception(SQLIntegrityConstraintViolationException e) {

        if (e.getMessage().contains("Duplicate entry")) {
            log.info("用户输入数据重复，无需管理");
            return Result.error(e.getMessage().split(" ")[2] + "字段重复，请重新输入");
        }
        return Result.error("服务器异常");
    }

    /**
     * 这个注解是要捕获的异常类型，参数就是类型
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RepetitionException.class)
    public Result<String> Exception(RepetitionException e) {
        log.info("用户输入数据重复，无需管理");
        return Result.error("\"" + e.getMessage() + "\"这个类名重复，请重新输入");
    }

    /**
     * 这个异常是对绑定了菜品进行删除时抛出的异常进行捕获
     *
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public Result<String> Exception(CustomException e) {
        log.info("用户输入数据重复，无需管理");
        return Result.error(e.getMessage());
    }

    /**
     * 捕获异常
     *
     * @param e
     * @return
     */
//    @ExceptionHandler(Exception.class)
//    public Result<String> Exception(Exception e) {
//        log.info(e.getMessage());
//        return Result.error("您的网络不佳，请稍后再试");
//    }

}
